package com.haobo.controller;

import com.haobo.pojo.Role;
import com.haobo.pojo.User;
import com.haobo.service.RoleService;
import com.haobo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * ClassName:UserController
 * Package:com.haobo.controller
 * Description:
 *
 * @Date:2021/5/28 20:46
 * @Author:haobo
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @RequestMapping("/user_list")
    public ModelAndView user_list(){
        ModelAndView modelAndView = new ModelAndView();
        List<User> userList = userService.list();
        //设置模型
        modelAndView.addObject("userList",userList);
        //设置视图
        modelAndView.setViewName("user-list");
        return modelAndView;
    }

    @RequestMapping("/user_addUI")
    public ModelAndView user_addUI(){
        ModelAndView modelAndView = new ModelAndView();
        List<Role> roleList = roleService.list();
        modelAndView.addObject("roleList",roleList);
        modelAndView.setViewName("user-add");
        return modelAndView;
    }

    @RequestMapping("/user_add")
    public String user_add(User user,Long[] roleIds){
        userService.user_add(user,roleIds);
        return "redirect:/user/user_list";
    }

    @RequestMapping("/delUser/{userId}")
    public String delUser(@PathVariable("userId") Long userId){
        userService.delUser(userId);
        return "redirect:/user/user_list";
    }

    @RequestMapping("user_login")
    public String user_login(String username, String password, HttpSession session) throws EmptyResultDataAccessException {
        User user = userService.user_login(username,password);
        if(user!=null){
            //登陆成功 将user存储到session
            session.setAttribute("user",user);
            return "redirect:/index.jsp";
        }
        return "redirect:/login.jsp";
    }

}
